# -*- coding: UTF-8 -*-
# @Time : 2022/1/13 0013 11:31
# @Author : lyw
# @Remark :
from mxsoftpy import Server
try:
    from opm_pyirm import GetStatusById
except ImportError:
    try:
        from bsmiddle import GetStatusById
    except ImportError:
        def GetStatusById(*args):
            return 1, 2

from db.common.IOTManager.AirConditioner.air_conditioner import ACSelectDB
from db.common.IOTManager.AirConditioner.modbus_ac import ACSelectDB as ModbusAC
from db.common.IOTManager.GasDetector.gas_detector import GASDeviceSelectDB
from db.common.IOTManager.Public.public import IOTAllDeviceDB
from db.common.IOTManager.TemHumidity.humidity import TemHumidityCheckDB
from db.common.IOTManager.UpsDevice.dev_select import UPSSelectDB
from db.common.IOTManager.Water.water import WaterCheckDB
from model.common.IOTManager.iot_base import SRoomIOTMiddleModel

from server.common.IOTManager.PowerCabinet.power_cabinet import PowerDeviceSelectServer
from server.public.IOTManager.server_base import IOTBaseServer
from utils.public.params_method import paging_data, get_pagination_params


class IOTAllDeviceServer(IOTBaseServer):
    __db__ = IOTAllDeviceDB
    __model__ = SRoomIOTMiddleModel

    def select(self, **kwargs):
        # 查找 系统的设备
        device_list: list = self.db.get_device(kwargs.get("name", ""))
        # 把门禁设备追加到设备列表
        device_list.extend(self.db.get_janitor(kwargs.get("name", "")))
        return device_list

    def list(self, **kwargs):
        """
        获取全部设备
        @param kwargs:
        @return:
        """
        search_type_dict = {"0": self.select, "1": UPSSelectDB().query_device, "2": None,
                            "3": TemHumidityCheckDB().read,
                            "5": GASDeviceSelectDB().query_device, "6": WaterCheckDB().read,
                            "7": ACSelectDB().query_device,
                            "9": PowerDeviceSelectServer().select, "11": ModbusAC().query_device,
                            "12": self.db.get_janitor}
        search_fun = search_type_dict.get(kwargs.get("search_type"), self.select)
        res_dict = []
        if search_fun:
            # kwargs["name"] = kwargs.get("search", "")
            res_dict = search_fun(name=kwargs.get("search", ""))

        if isinstance(res_dict, dict):
            if res_dict.get("device_data") is not None:
                res_dict = res_dict["device_data"]
            else:
                res_dict = res_dict["data"]
        # 清理字段
        # self.clear_filed(res_dict)
        # 获取基本信息
        res_dict = self.data_process(kwargs, res_dict)

        res_dict = paging_data(res_dict, **get_pagination_params(kwargs))
        return res_dict

    @staticmethod
    def clear_filed(res_dict):
        """
        清理字段
        @param res_dict:
        @return:
        """
        for key in ["dev_count", "ups_count", "normal", "warning", "offline"]:
            if res_dict.get(key) is not None:
                del res_dict[key]

    def data_process(self, kwargs, device_list) -> list:
        """
        数据处理
        @param kwargs:
        @param device_list:
        @return:
        """
        device_type_dict = {"UpsDevice": "Ups监测", "video": "视频监测", "TemperatureHumidity": "温湿度",
                            "GasDetector": "烟感监测", "Water": "漏水监测",
                            "AirConditioning": "精密空调", "Power": "配电柜", "ModbusAC": "普通空调", "janitor": "门禁"}
        res_list = []
        for device_dict in device_list:
            # 统一字段
            device_code, name, device_type = self.unify_filed(device_dict)
            device_dict.clear()

            device_dict["code"] = device_code
            device_dict["name"] = name
            # 获取状态
            device_dict["state"] = self.set_state(GetStatusById(device_code)[1])
            mx_type = device_type.split("\\")
            device_dict["type_name"] = device_type_dict.get(mx_type[1] if len(mx_type) >= 2 else mx_type[0], "") if len(
                mx_type) >= 1 else ""

            device_dict["type"] = mx_type[1] if len(mx_type) >= 2 else mx_type[0] if len(mx_type) >= 1 else ""
            # TODO 需要查询 机房关联的设备的中间表
            relevance_name, middle_value, relevance_state = self.query_sroom_iot_middle(kwargs, device_dict)
            device_dict["relevance"] = relevance_name
            device_dict["priority"] = middle_value["priority"]
            device_dict["middle_code"] = middle_value["code"]
            # 关联判断

            if kwargs.get("sroom_code"):
                if relevance_state != "0":
                    res_list.append(device_dict)
            else:
                if relevance_state in kwargs.get("relevance", "").split(";"):
                    res_list.append(device_dict)
        return res_list

    @staticmethod
    def unify_filed(device_dict):
        """
        统一字段
        @param device_dict:
        @return:
        """
        # 获取设备code
        if device_dict.get("device_id") is not None:
            device_code = device_dict.pop("device_id")
        elif device_dict.get("door_id") is not None:
            device_code = device_dict.pop("door_id")
        else:
            device_code = device_dict.pop("code", "")
        # 增加名字
        if device_dict.get("mxlabel") is not None:
            name = device_dict.pop("mxlabel")
        elif device_dict.get("label") is not None:
            name = device_dict.pop("label")
        elif device_dict.get("name") is not None:
            name = device_dict.pop("name")
        elif device_dict.get("ac_name") is not None:
            name = device_dict.pop("ac_name")
        else:
            name = ""

        if device_dict.get("mxdevicetype") is not None:
            device_type = device_dict.pop("mxdevicetype")
        else:
            device_type = device_dict.pop("type", "")
        return device_code, name, device_type

    def query_sroom_iot_middle(self, kwargs, device_dict):
        """
        查找中间表
        @param kwargs:
        @param device_dict:
        @return:
        """

        mid_value = self.db.query_middle_all(
            self.model(device_type=device_dict["type"], iot_code=device_dict["code"],
                       sroom_code=kwargs["sroom_code"] if kwargs.get("sroom_code") else "*"))
        if mid_value:
            return self.db.retrieve(mid_value[0]["sroom_code"])[1]["parent_name"], mid_value[0], "1"
        else:
            return "否", {"code": "0", "priority": 0}, "0"
